package com.blank.white.common.util;

import com.blank.white.common.enums.CachePreEnum;
import com.github.benmanes.caffeine.cache.LoadingCache;

import java.util.Objects;
import java.util.function.Supplier;


public class CacheUtil {


    public static Boolean lockByConfigId(Long key, LoadingCache<String, Object> loadingCache) {
        return lock(CachePreEnum.CONFIG_ID_LOCK.getName(), key.toString(), loadingCache);
    }

    /**
     * caffeine 上锁
     *
     */
    public static Boolean lock(String preName,String key, LoadingCache<String, Object> loadingCache) {
        //  查询使用已经存在该key
        Integer  flag= (Integer) loadingCache.getIfPresent(preName+key);
        // 如果存在则上锁失败
        if (Objects.nonNull(flag)) {
            return false;
        }
        // 如果不存在则进行上锁
        loadingCache.put(preName+key, 1);
        return true;
    }


    /**
     * 获取缓存 指定Key值的缓存
     * @param key
     * @param loadingCache
     * @param supplier
     * @param <T>
     * @return
     */
    public static <T> T getChace(String key, LoadingCache<String, Object> loadingCache, Supplier<T> supplier) {
        T v = (T) loadingCache.get(key);
        if (Objects.isNull(v)) {
            v = supplier.get();
            if (Objects.nonNull(v)) {
                loadingCache.put(key, v);
            }
        }
        return v;
    }

}
